


import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:little_game/redux/GlobalStore.dart';
import 'package:little_game/redux/action.dart';
import 'package:redux/redux.dart';

import 'animateWidget.dart';



class Test extends StatelessWidget{
  final int xi;
  final int yi;
  final List<Widget> iconList;
  Test({Key key,this.xi,this.yi,this.iconList}):super(key:key);
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        body: Center(
          child: StoreConnector(
            converter: (Store<GlobalStore> s){
              return SConnectorObj.init(widgetList: _initWidgetListMap(),list: s.state.gameList,g: s);
            },
            builder: (ctx, SConnectorObj vm){
              List wl = vm.widgetList;
              List cl = vm.list;
              List _quene = vm.quene;
              if(xi != yi){
                return errorWidget("x和y不相等");
              }
              if(wl.length == 0) return errorWidget("没有元素");
              if(xi + yi != iconList.length){
                return errorWidget("元素长度不正确!");
              }
              if(_success(cl, 2)){
                return Text("恭喜你完成啦 \u{1f44d} \n 耗时:");
              }
              return GridView.builder(
                physics: NeverScrollableScrollPhysics(),
                itemCount: xi*yi,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: yi,
                    crossAxisSpacing: 4.0,
                    mainAxisSpacing: 4.0,
                    childAspectRatio: 0.7
                ),
                itemBuilder: (BuildContext context,int i){
                  int t = i + 1;
                  // int x = i % xi; //数组列索引
                  // int y = (i - x) ~/ yi;//求数组行索引

                  var itemx = cl[i];
                  // var itemx = item[x];
                  var pitem = wl[i];
                  // print("===>$itemx==$i");

                  if(itemx == 2){
                    return Container(
                      alignment: Alignment.center,
                      width: 80.0,
                      height: 220.0,
                      decoration: BoxDecoration(
                        color: _judgeColor(2,t),
                      ),
                    );
                  };

                  return AnimationLG(
                    duration: Duration(milliseconds: 200),
                    child: Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: Colors.green,//_judgeColor(0,t),
                          border: Border.all()
                      ),
                      child: _judgeWidget(1,pitem['view'],t),
                    ),
                    childR: Container(
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: _judgeColor(1,t),
                          border: Border.all()
                      ),
                      child: _judgeWidget(0,pitem['view'],t),
                    ),
                    onTap: (AnimationController controller,Animation animate) async{
                      // if(_valueNotifier.value == 0){
                      //   Toast.showText("请先开始计时");
                      //   return;
                      // };
                      print("==>$cl");
                      if(cl[i] == 1) return;
                      // cl[i] = 1;


                      Map<String,dynamic> m = {"i":i,'v':controller};

                      cl[i] = 1;
                      _quene.add(m);
                      controller.forward();
                      _dealQuene(m,vm,wl);
                      // if(_quene.length >=2){
                      //
                      //   return;
                      // }

                    },
                  );
                },
              );
            },
            onInit: (s){
                print("==$s");
            },
          ),
        )
    );
  }

  //构建元素列表 list map
  List _buildList(){
    //return [1,2,3,4,5,6,7,8];
    List nl = iconList;
    //List nl = [1,2,3,4,5,6,7,8];
    int ln = nl.length;
    List rl = new List();
    for(int i = 0; i< ln; i++){
      rl.add({"view":nl[i],"value":i});
    };
    return rl;
  }

  //初始化图像列表
  List _initWidgetListMap(){
    List n = _buildList();
    n.addAll(_buildList());
    int len = xi * yi;
    List out = [];
    for(int i = 0; i < len;i++){
        int idx = Random().nextInt(n.length);
        out.add(n[idx]);
        n.removeAt(idx);
    };
    return out;
  }

  Widget errorWidget(String text){
      return Text(text,style: TextStyle(color: Colors.red),);
  }


  //颜色判断

 Color _judgeColor(int b,int f){
   switch(b){
     case 0:
       return Colors.purpleAccent.withOpacity(0.5);
     case 2:
       return Colors.transparent;
     default:
       return Colors.blueAccent.withOpacity(0.5);
   }
 }

 Widget _judgeWidget(int ve,Widget widget, int t){



   switch(ve){
     case 0:
       return Text('$t');
     case 2:
       return Visibility(visible: false,child: Text('d'),);
     default:
       return  widget;
   }
 }

 //二元数组变成一元数组
 List _buildLongList(List<dynamic> tl){
    List a = [];
    tl.forEach((dynamic item){
        item.forEach((c){
          a.add(c);
        });
    });
    return a;
 }

  //判断相同

  _isSame(SConnectorObj vm,List quene, List wl){
    int l = quene[0]["i"];
    int r = quene[1]["i"];
    if(wl[l]["value"] == wl[r]["value"]){
      vm.list[l] = 2;
      vm.list[r] = 2;
      vm.quene.clear();

    }
  }
  //处理队列
  _dealQuene(Map<String,dynamic> map,SConnectorObj vm,List wl){
    List quene = vm.quene;
    int len = quene.length;
    if(len - 2 < 0) return;
    List compare = quene.sublist(len - 2);
    List pop = quene.sublist(0, len -2);
    // if(pop.length == 0) return;
    print("==>$compare===$pop");
    _isSame(vm, compare, wl);
    if(pop.length == 0){
      vm.dispatch(vm.list);
      return;
    }
    List<Future> fl = new List();
    pop.forEach((item){
      int i = item["i"];
      fl.add(item["v"].reverse().then((f){
        vm.list[i] = 0;
      }));
      quene.remove(item);

    });
    Future.wait(fl).then((v){
        vm.dispatch(vm.list);
    });
  }



  //判断是否完成
  bool _success(List list,int status){
     int len = list.length;
     bool s = true;
     for(int i = 0; i < len;i++){
       if(list[i] != status){
          s  = false;
       }
     };
     return s;
  }
}


class SConnectorObj {

  static SConnectorObj _instances;
  Store store;
  List widgetList;
  List list;
  List quene = [];
  Timer _time;
  SConnectorObj(List w,List l,Store g){
    this.widgetList = w;
    this.list = l;
    this.store = g;
  }
  static SConnectorObj init({List widgetList,List list,Store g}){
    if(_instances == null) {
      _instances = new SConnectorObj(widgetList,list,g);
    }
    return _instances;
  }
  void dispatch(List nl){
    this.list = nl;
    this.store.dispatch(ListRefreshAction(nl));
  }



}